package ch10_IO流与文件.案例实践_程序快照机;

import javax.swing.*;
import java.io.*;

/**
 * @author 挚爱之夕
 * @date 2021/8/27 - 08 - 27 - 20:45
 * @Description: ch10.案例实践_程序快照机
 * @Version: 1.0
 */
public class SnapshotDemo {
    public static void main(String[] args) {
        new MyFrame().setVisible(true);
    }
}
class Snapshot {
    String file = "D:/SnapShot.dat";    //快照文件

    void save(MyFrame f) {   //写出快照
        try (FileOutputStream fout = new FileOutputStream(file);
             ObjectOutputStream out = new ObjectOutputStream(fout)) {
            out.writeObject(f); //序列化
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("写出快照时发生了 I/O错误！");
        }
    }

    MyFrame load() {    //读入快照
        MyFrame f = null;   //存放恢复的窗口
        try (FileInputStream fin = new FileInputStream(file);
             ObjectInputStream in = new ObjectInputStream(fin)) {
            f = (MyFrame) in.readObject();  //反序列化并造型
        } catch (ClassNotFoundException | IOException e) {
            System.out.println("读入快照时发生了 I/O 错误！");
        }
        return f;   //返回窗口对象
    }


}

class MyFrame extends JFrame implements Serializable {
    JButton saveBtn = new JButton("保存快照");
    JButton loadBtn = new JButton("恢复快照");
    JPanel panel = new JPanel();
    JTextArea ta = new JTextArea("初始文字");
    JScrollPane sp = new JScrollPane(ta);
    transient Snapshot snapshot = new Snapshot();//不序列化此字段

    public void setSnapshot(Snapshot snapshot) {
        this.snapshot = snapshot;
    }

    MyFrame() {
        init();
        saveBtn.addActionListener(e -> snapshot.save(this));  //单击保存快照按钮
        loadBtn.addActionListener(e -> {  //单击恢复快照按钮
            MyFrame f = snapshot.load();
            f.setSnapshot(new Snapshot());//此行不可少（因未序列化MyFrame的snapshot字段）
            f.setVisible(true);//显示恢复的窗口
            this.dispose(); //关闭原来的窗口
        });
    }

    void init() {
        this.setLayout(null);
        this.setTitle("程序快照机");
        this.setSize(300,300);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        sp.setSize(300,200);
        sp.setLocation(0,0);
        this.add(sp);
        panel.setSize(300,50);
        saveBtn.setSize(50,30);
        loadBtn.setSize(50,30);
        panel.add(saveBtn);
        panel.add(loadBtn);
        panel.setLocation(0,200);
        this.add(panel);
        this.setVisible(true);
    }
}



